/* nothing */
(function(global){
    function request(method, id, data, cb){
	var xhr = new XMLHttpRequest();
	var addr = '/data'
	if(id)
	    addr += '/' + id;
	xhr.open(method, addr, true);
	xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
	xhr.onloadend = function(e){
	    if(cb)
		cb(JSON.parse(xhr.response));
	}
	if(data)
	    xhr.send(JSON.stringify(data));
	else
	    xhr.send();
    }

    function getAll(cb){
	request('GET', null, null, cb);
    }

    function deleteOne(id, cb){
	request('DELETE', id, {id: id}, cb);
    }

    function postOne(data, cb){
	request('POST', null, data, cb);
    }

    function putOne(data, cb){
	request('PUT', data._id, data, cb);
    }

    var hasid_checkbox = document.getElementById('hasid');
    var id_input = document.getElementById('id');
    var name_input = document.getElementById('name');
    var age_input = document.getElementById('age');
    var gender_input = document.getElementById('gender');
    var submit_btn = document.getElementById('submit');

    function makeEntry(data)
    {
	var p = document.createElement('div');
	p.className = 'col-xs-6'
	var closeBtn = document.createElement('div')
	closeBtn.innerHTML = 'X';
	closeBtn.className = 'btn-close';
	// when delete button is clicked
	closeBtn.onclick = function(){
	    p.parentNode.removeChild(p);
	    deleteOne(data._id, function(result){alert(JSON.stringify(result));});
	}
	var c = document.createElement('div');
	c.className = 'entry';
	var id = makeLine('ID:', data._id);
	// fill the id input with this id
	id.onclick = function(){};
	c.appendChild(id);
	c.appendChild(makeLine('Name:', data.name));
	c.appendChild(makeLine('Age:', data.age));
	c.appendChild(makeLine('Gender:', data.gender));
	c.appendChild(closeBtn);
	p.appendChild(c);
	return p;
    }

    function makeLine(prop, val){
	var p = document.createElement('p');
	p.innerHTML = '<b>'+prop+'</b>'+val;
	return p;
    }

    var contents = document.getElementById('contents')

    function refreshContent(){
	contents.innerHTML = '';
	getAll(function(data){
	    for(var i = 0; i < data.length; i++)
	    {
		contents.appendChild(makeEntry(data[i]));
	    }
	});
    };

    global.refershContent = refreshContent;

    refreshContent();

    // id input & checkbox
    hasid_checkbox.onchange = function(){
	id_input.disabled = !hasid_checkbox.checked;
    }
    id_input.disabled = true;

    // collect info from form
    function collectInfo(){
	var info = {};
	if(hasid_checkbox.checked)
	    info._id = id_input.value;
	info.name = name_input.value;
	info.age = age_input.value;
	info.gender = gender_input.value;
	return info;
    }

    // submit button
    submit_btn.onclick = function(){
	var info = collectInfo();
	var method = null
	if(typeof info._id === 'undefined')
	    method = postOne;
	else
	    method = putOne;
	method(info, function(result){refreshContent();alert(JSON.stringify(result));});
    }
    
})(this);
